package com.zwcl.common.web.handler;

import com.zwcl.common.core.domain.entity.ApiResult;
import com.zwcl.common.core.enums.ExceptionCode;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局响应处理器
 * by xyp
 */
@RestControllerAdvice(basePackages = "com.zwcl")//要扫描的包
public class GlobalResponseAdvice implements ResponseBodyAdvice {
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        //如果body为空，返回默认信息
        if (body == null) {
            return ApiResult.result(true);
        }
        //匹配ResponseResult
        if (body instanceof ApiResult) {
            return body;
        }
        /**
         * 其他情况直接将返回的信息直接塞在data中
         */
        return ApiResult.result(ExceptionCode.SUCCESS,body);
    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }


}
